/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import dao.exceptions.IllegalOrphanException;
import dao.exceptions.NonexistentEntityException;
import dao.exceptions.RollbackFailureException;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.transaction.UserTransaction;
import pojo.Extra;
import pojo.Extraprice;
import java.util.ArrayList;
import java.util.Collection;

/**
 *
 * @author A7med Kotb
 */
public class ExtraJpaController implements Serializable {

    public ExtraJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Extra extra) throws RollbackFailureException, Exception {
        if (extra.getExtrapriceCollection() == null) {
            extra.setExtrapriceCollection(new ArrayList<Extraprice>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Collection<Extraprice> attachedExtrapriceCollection = new ArrayList<Extraprice>();
            for (Extraprice extrapriceCollectionExtrapriceToAttach : extra.getExtrapriceCollection()) {
                extrapriceCollectionExtrapriceToAttach = em.getReference(extrapriceCollectionExtrapriceToAttach.getClass(), extrapriceCollectionExtrapriceToAttach.getId());
                attachedExtrapriceCollection.add(extrapriceCollectionExtrapriceToAttach);
            }
            extra.setExtrapriceCollection(attachedExtrapriceCollection);
            em.persist(extra);
            for (Extraprice extrapriceCollectionExtraprice : extra.getExtrapriceCollection()) {
                Extra oldExtraIdOfExtrapriceCollectionExtraprice = extrapriceCollectionExtraprice.getExtraId();
                extrapriceCollectionExtraprice.setExtraId(extra);
                extrapriceCollectionExtraprice = em.merge(extrapriceCollectionExtraprice);
                if (oldExtraIdOfExtrapriceCollectionExtraprice != null) {
                    oldExtraIdOfExtrapriceCollectionExtraprice.getExtrapriceCollection().remove(extrapriceCollectionExtraprice);
                    oldExtraIdOfExtrapriceCollectionExtraprice = em.merge(oldExtraIdOfExtrapriceCollectionExtraprice);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Extra extra) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Extra persistentExtra = em.find(Extra.class, extra.getId());
            Collection<Extraprice> extrapriceCollectionOld = persistentExtra.getExtrapriceCollection();
            Collection<Extraprice> extrapriceCollectionNew = extra.getExtrapriceCollection();
            List<String> illegalOrphanMessages = null;
            for (Extraprice extrapriceCollectionOldExtraprice : extrapriceCollectionOld) {
                if (!extrapriceCollectionNew.contains(extrapriceCollectionOldExtraprice)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Extraprice " + extrapriceCollectionOldExtraprice + " since its extraId field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Collection<Extraprice> attachedExtrapriceCollectionNew = new ArrayList<Extraprice>();
            for (Extraprice extrapriceCollectionNewExtrapriceToAttach : extrapriceCollectionNew) {
                extrapriceCollectionNewExtrapriceToAttach = em.getReference(extrapriceCollectionNewExtrapriceToAttach.getClass(), extrapriceCollectionNewExtrapriceToAttach.getId());
                attachedExtrapriceCollectionNew.add(extrapriceCollectionNewExtrapriceToAttach);
            }
            extrapriceCollectionNew = attachedExtrapriceCollectionNew;
            extra.setExtrapriceCollection(extrapriceCollectionNew);
            extra = em.merge(extra);
            for (Extraprice extrapriceCollectionNewExtraprice : extrapriceCollectionNew) {
                if (!extrapriceCollectionOld.contains(extrapriceCollectionNewExtraprice)) {
                    Extra oldExtraIdOfExtrapriceCollectionNewExtraprice = extrapriceCollectionNewExtraprice.getExtraId();
                    extrapriceCollectionNewExtraprice.setExtraId(extra);
                    extrapriceCollectionNewExtraprice = em.merge(extrapriceCollectionNewExtraprice);
                    if (oldExtraIdOfExtrapriceCollectionNewExtraprice != null && !oldExtraIdOfExtrapriceCollectionNewExtraprice.equals(extra)) {
                        oldExtraIdOfExtrapriceCollectionNewExtraprice.getExtrapriceCollection().remove(extrapriceCollectionNewExtraprice);
                        oldExtraIdOfExtrapriceCollectionNewExtraprice = em.merge(oldExtraIdOfExtrapriceCollectionNewExtraprice);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = extra.getId();
                if (findExtra(id) == null) {
                    throw new NonexistentEntityException("The extra with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Extra extra;
            try {
                extra = em.getReference(Extra.class, id);
                extra.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The extra with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<Extraprice> extrapriceCollectionOrphanCheck = extra.getExtrapriceCollection();
            for (Extraprice extrapriceCollectionOrphanCheckExtraprice : extrapriceCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Extra (" + extra + ") cannot be destroyed since the Extraprice " + extrapriceCollectionOrphanCheckExtraprice + " in its extrapriceCollection field has a non-nullable extraId field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(extra);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Extra> findExtraEntities() {
        return findExtraEntities(true, -1, -1);
    }

    public List<Extra> findExtraEntities(int maxResults, int firstResult) {
        return findExtraEntities(false, maxResults, firstResult);
    }

    private List<Extra> findExtraEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Extra.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Extra findExtra(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Extra.class, id);
        } finally {
            em.close();
        }
    }

    public int getExtraCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Extra> rt = cq.from(Extra.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
